using Microsoft.AspNetCore.Mvc;
using ZGL.Api.Services;
using System.Threading.Tasks;
using System;

namespace ZGL.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class SerialPortController : ControllerBase
    {
        private readonly SerialPortService _serialPortService;

        public SerialPortController(SerialPortService serialPortService)
        {
            _serialPortService = serialPortService ?? throw new ArgumentNullException(nameof(serialPortService));
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        [HttpPost("send")]
        public async Task<IActionResult> SendData([FromBody] byte[] data)
        {
            try
            {
                var success = await _serialPortService.SendDataAsync(data);
                return Ok(new { Success = success });
            }
            catch (Exception ex)
            {
                return BadRequest($"Failed to send data: {ex.Message}");
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        [HttpGet("receive")]
        public async Task<IActionResult> ReceiveData([FromQuery] int timeout = 1000)
        {
            try
            {
                var data = await _serialPortService.ReceiveDataAsync(timeout);
                if (data == null)
                {
                    return Ok(new { Message = "No data received within timeout period" });
                }
                return Ok(new { Data = Convert.ToBase64String(data) });
            }
            catch (Exception ex)
            {
                return BadRequest($"Failed to receive data: {ex.Message}");
            }
        }

        /// <summary>
        /// 发送并等待响应
        /// </summary>
        [HttpPost("sendandreceive")]
        public async Task<IActionResult> SendAndReceive(byte[] data, int timeout = 1000)
        {
            try
            {
                var response = await _serialPortService.SendAndReceiveAsync(data, timeout);
                if (response == null)
                {
                    return Ok(new { Message = "No response received within timeout period" });
                }
                return Ok(new { Response = Convert.ToBase64String(response) });
            }
            catch (Exception ex)
            {
                return BadRequest($"Failed to send and receive data: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查端口状态
        /// </summary>
        [HttpGet("status")]
        public IActionResult GetPortStatus()
        {
            try
            {
                var (sendPortStatus, receivePortStatus) = _serialPortService.GetPortStatus();
                return Ok(new
                {
                    SendPortStatus = sendPortStatus ? "Open" : "Closed",
                    ReceivePortStatus = receivePortStatus ? "Open" : "Closed"
                });
            }
            catch (Exception ex)
            {
                return BadRequest($"Failed to get port status: {ex.Message}");
            }
        }

        /// <summary>
        /// 重新打开端口
        /// </summary>
        [HttpPost("reopen")]
        public IActionResult ReopenPorts()
        {
            try
            {
                _serialPortService.ReopenPorts();
                return Ok(new { Message = "Ports reopened successfully" });
            }
            catch (Exception ex)
            {
                return BadRequest($"Failed to reopen ports: {ex.Message}");
            }
        }
    }
} 